<?php
error_reporting(E_ERROR);
include_once '..\clases\ConexionBD.php';
include_once '..\utils\ConstantesGlobales.php';
include_once '..\daos\BackupDAO.php';
require_once '..\dropbox\autoload.php';

session_start();

$conexionBD = unserialize($_SESSION['conexionBD']); /*@var $conexionBD ConexionBD*/
$accion = $_POST['accion'];

if($accion == "buscar"){
    
    $query = $GLOBALS['consultaPorDocumentoCliente'] . "" . $_POST['busdocumento'];
    $conexionBD->abrirConexion();
    $result = mysql_query($query,$conexionBD->getConexion());
    $pacienteNom = "";
    $contador = 0;
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $pacienteNom = $row['TIPONIT'] ." ". $row['NIT'] ." ". $row['NOMBRES'] ." ". $row['APELLIDOS'];
        $contador += 1;
    }
    $conexionBD->cerrarConexion();
    
    if($contador == 1){
        $_SESSION['resultado'] = "encontro";
        $_SESSION['nombrePaciente'] = $pacienteNom;
        $_SESSION['busdocumento'] = $_POST['busdocumento'];  
    }elseif($contador == 0){
        $_SESSION['resultado'] = "noencontro";
    }
    
    session_write_close();
    
    header('Location: ../principal.php');
    exit();
    
}elseif($accion == "nuevo"){
    
    unset($_SESSION['busdocumento']);
    unset($_SESSION['nombrePaciente']);
    
    header('Location: ../formularios/FormularioIdentAnte.php');
    exit();
}
elseif ($accion == "existe") {
    
       
    $docBus = $_SESSION['busdocumento'];
    $query = $GLOBALS['consultaClienteDocumentoTodo'] . "" . $docBus;
    $conexionBD->abrirConexion();
    $resultTodo = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
    while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){
        $_SESSION['tiponit'] = $row['TIPONIT'];
        $_SESSION['nit'] = $row['NIT'];   
        $_SESSION['nombre'] = $row['NOMBRES'];
        $_SESSION['apellido'] = $row['APELLIDOS'];
        $_SESSION['fechanac'] = $row['FECHANAC'];
        $_SESSION['edad'] = $row['EDAD'];
        $_SESSION['sexo'] = $row['SEXO'];
        $_SESSION['lugarnam'] = $row['LUGARNAC'];
        $_SESSION['estacivil'] = $row['ESTCIVIL'];
        $_SESSION['dirbarrio'] = $row['DIRBARRIO'];
        $_SESSION['telsred'] = $row['TELRESD'];
        $_SESSION['celular'] = $row['CELULAR'];
        $_SESSION['ocupacion'] = $row['OCUPACION'];
        $_SESSION['telofice'] = $row['TELOFICINA'];
        $_SESSION['email'] = $row['EMAIL'];
        $_SESSION['eps'] = $row['EPS'];
        $_SESSION['vinc'] = $row['VINC'];
     }

    $query = "SELECT FAMILIARES, PERSONALES, QUIRURGICOS FROM antecedentes WHERE NITPACIENTE = '$docBus' AND 
        FECHACONS = (SELECT MAX(FECHACONS) FROM antecedentes WHERE NITPACIENTE = '$docBus')";
    $conexionBD->abrirConexion();
    $result = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){    
        $_SESSION['familiares'] = $row['FAMILIARES'];
        $_SESSION['personales'] = $row['PERSONALES'];
        $_SESSION['quirugicos'] = $row['QUIRURGICOS'];
    }
    
    if($_SESSION['sexo'] == "F")
    {
        $query = "SELECT GINECO, ANIOS, CICLOS, G, P, A, C, QX FROM datamujer WHERE NITPACIENTE = '$docBus' 
            AND FECHACONS = (SELECT MAX(FECHACONS) FROM datamujer WHERE NITPACIENTE = '$docBus')";
        $conexionBD->abrirConexion();
        $result = mysql_query($query,$conexionBD->getConexion());
        $conexionBD->cerrarConexion();
        
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        
        $_SESSION['gineco'] = $row['GINECO']; //es un antecedente
        $_SESSION['anosmenarquia'] = $row['ANIOS'];
        $_SESSION['ciclos'] = $row['CICLOS'];
        $_SESSION['gestaciones'] = $row['G'];
        $_SESSION['partos'] = $row['P'];
        $_SESSION['abortos'] = $row['A'];
        $_SESSION['cesareas'] = $row['C'];
        $_SESSION['cirugias'] = $row['QX'];
        
    }
       
    session_write_close();
    
    header('Location: ../formularios/FormularioIdentAnte.php');
    exit();
    
}elseif ($accion == "consultar") {
    
    $docBus = $_SESSION['busdocumento'];
    $query = $GLOBALS['consultaClienteDocumentoTodo'] . "" . $docBus;
    $conexionBD->abrirConexion();
    $resultTodo = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
    while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){
        $_SESSION['tipoDocPaciente'] = $row['TIPONIT'];
        $_SESSION['documentoPaciente'] = $row['NIT'];   
        $_SESSION['nombresPaciente'] = $row['NOMBRES'];
        $_SESSION['apellidoPacientes'] = $row['APELLIDOS'];
        $_SESSION['fechaNacimientoPaciente'] = $row['FECHANAC'];
        $_SESSION['edad'] = $row['EDAD'];
        $_SESSION['sexoPaciente'] = $row['SEXO'];
        $_SESSION['lugarNacimientoPaciente'] = remplazarTildez($row['LUGARNAC']);
        $_SESSION['estadoCivilPaciente'] = $row['ESTCIVIL'];
        $_SESSION['direccionPaciente'] = $row['DIRBARRIO'];
        $_SESSION['telResPaciente'] = $row['TELRESD'];
        $_SESSION['celularPaciente'] = $row['CELULAR'];
        $_SESSION['ocupacionPaciente'] = $row['OCUPACION'];
        $_SESSION['telOficinaPaciente'] = $row['TELOFICINA'];
        $_SESSION['emailPaciente'] = $row['EMAIL'];
        $_SESSION['epsPaciente'] = $row['EPS'];
        $_SESSION['vinculacionPaciente'] = $row['VINC'];
     }
     $_SESSION['nombrePacienteCompleto'] = $_SESSION['nombresPaciente'] ." " . $_SESSION['apellidoPacientes'];
     
     $query = "SELECT FAMILIARES, PERSONALES, QUIRURGICOS FROM antecedentes WHERE NITPACIENTE = '$docBus' AND 
        FECHACONS = (SELECT MAX(FECHACONS) FROM antecedentes WHERE NITPACIENTE = '$docBus')";
    $conexionBD->abrirConexion();
    $resultTodo = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
    while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){    
        $_SESSION['antecedenteFamiliares'] = $row['FAMILIARES'];
        $_SESSION['antecedentePersonales'] = $row['PERSONALES'];
        $_SESSION['antecedentesQuirurgicos'] = $row['QUIRURGICOS'];
    }
    
    $query = "SELECT distinct(acu.FECHACONS) 
        FROM paciente pac, acudyacomp acu 
        WHERE pac.nit = acu.nitpaciente AND pac.nit = '$docBus' 
        ORDER BY 1 DESC";
    
    $conexionBD->abrirConexion();
    $resultTodo = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
    $listaFechasHTML = "";
    $primerFecha = "";
    $contFecha = 0;
    while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){    
        $listaFechasHTML = $listaFechasHTML . '<option value="'.$row['FECHACONS'].'">'.$row['FECHACONS'].'</option>';
        if($contFecha == 0){
            $primerFecha = $row['FECHACONS'];
            $contFecha = 1;
        }
    }
    
    $_SESSION['listaFechasHTML'] = $listaFechasHTML;
    
    //Acompañante y Acudiente
    $query = "SELECT NOMBREACU, TELACU, PARENTACU, NOMBREACO, TELACO, PARENTACO
    FROM paciente pac
    JOIN acudyacomp acu ON pac.nit = acu.nitpaciente
    WHERE pac.nit =  '$docBus'
    AND acu.fechacons =  '$primerFecha'";
    
    $conexionBD->abrirConexion();
    $resultTodo = mysql_query($query,$conexionBD->getConexion());
    $conexionBD->cerrarConexion();
    
     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){    
          $_SESSION['datosAcudiente'] = "Nombre: ".$row['NOMBREACU']." Tel:".$row['TELACU']." Parentesco:".$row['PARENTACU'];
          $_SESSION['datosAcmponante'] = "Nombre: ".$row['NOMBREACO']." Tel:".$row['TELACO']." Parentesco:".$row['PARENTACO'];
     }
     
     //Diagnostico
     $query = "SELECT * FROM paciente pac JOIN diagnostico diag  ON pac.nit = diag.nitpaciente WHERE pac.nit = '$docBus' AND diag.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
          $_SESSION['diagnostico'] = $row['DIAGDESC'];
          $_SESSION['cie10'] = $row['CIE10'];
          $_SESSION['tipoDiag'] = $row['TIPODIAG'];
     }

     
     //Dinamica Patologico
     $query = "SELECT * FROM paciente pac JOIN dinapato dinpat  ON pac.nit = dinpat.nitpaciente WHERE pac.nit = '$docBus' AND dinpat.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
          $_SESSION['dinaPato'] = $row['DINAMPATOLO'];
     }
     
     //Examen Complementario
     $query = "SELECT * FROM paciente pac JOIN examcomp excp  ON pac.nit = excp.nitpaciente WHERE pac.nit = '$docBus' AND excp.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
         $_SESSION['examnComp'] = $row['EXAMPDESC'];
     }
     
     
     //Fisico
     $query = "SELECT * FROM paciente pac JOIN fisico fsc  ON pac.nit = fsc.nitpaciente WHERE pac.nit = '$docBus' AND fsc.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
           $_SESSION['presArt'] = $row['SISTOLE']."/".$row['DIASTOLE'];
           $_SESSION['frecCard'] = $row['FCARDIACA'];
           $_SESSION['frecResp'] = $row['FRESPIRA'];
           $_SESSION['peso'] = $row['PESO'];
           $_SESSION['talla'] = $row['TALLA'];
           $_SESSION['temp'] = $row['TEMPERATURA'];
     }
     
     //Fisico General
     $query = "SELECT * FROM paciente pac JOIN `general` gen  ON pac.nit = gen.nitpaciente WHERE pac.nit = '$docBus' AND gen.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
        $_SESSION['cabeza'] = $row['CABEZA'];
        $_SESSION['cuello'] = $row['CUELLO'];
        $_SESSION['torax'] = $row['TORAX'];
        $_SESSION['abdomen'] = $row['ABDOMEN'];
        $_SESSION['pelvis'] = $row['PELVIS'];
        $_SESSION['extremidades'] = $row['EXTREMIDADES'];
     }
     
     //Motivo
     $query = "SELECT * FROM paciente pac JOIN motivo mt  ON pac.nit = mt.nitpaciente WHERE pac.nit = '$docBus' AND mt.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
         $_SESSION['motivoConsulta'] = $row['MOTYENF'];
     }
     
     //Revsion por sistemas
     $query = "SELECT * FROM paciente pac JOIN revsistemas sis  ON pac.nit = sis.nitpaciente WHERE pac.nit = '$docBus' AND sis.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
            $_SESSION['sistDig'] = $row['DIGESTIVO'];
            $_SESSION['sisCard'] = $row['CARDIOVASCULAR'];
            $_SESSION['sistResp'] = $row['RESPIRATORIO'];
            $_SESSION['sistGeni'] = $row['GENITOURINARIO'];
            $_SESSION['sistOsteo'] = $row['OSTEOMUSCULAR'];
            $_SESSION['sistEndo'] = $row['ENDOCRINO'];
            $_SESSION['sistNerv'] = $row['NERVIOSO'];
            $_SESSION['sisPsico'] = $row['PSICOSOMATICO'];
     }
     
     //Tratamiento
     $query = "SELECT * FROM paciente pac JOIN tratamiento trt  ON pac.nit = trt.nitpaciente WHERE pac.nit = '$docBus' AND trt.fechacons = '$primerFecha'";
     
     $conexionBD->abrirConexion();
     $resultTodo = mysql_query($query,$conexionBD->getConexion());
     $conexionBD->cerrarConexion();

     while ($row = mysql_fetch_array($resultTodo, MYSQL_ASSOC)){ 
         $_SESSION['tratamiento'] = $row['TRATADESC'];
     }
    
    session_write_close();
    header('Location: ../formularios/FormularioConsulta.php');
    exit();
    
}elseif($accion == "backup"){
    
   $token = null;
   $handleLeer = fopen('..\data\token', 'r');
   if ($handleLeer) {
           while (($line = fgets($handleLeer)) !== false) {
              $token = trim($line);
           }
    }
    fclose($handleLeer);
    
    if($token == null && !isset($_POST['bttnenviar']))
    {
        $appInfo = Dropbox\AppInfo::loadFromJsonFile("..\data\login.json");
        $webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
        $authorizeUrl = $webAuth->start();
        
        $_SESSION['dropboxAut'] = "1. Ir a:  <a href=" . $authorizeUrl . " target=”_blank”>Autorizaci&oacute;n Dropbox.</a> <br>" 
            . "2. Click en \"Allow\" (puede que toque ingresar).<br>" 
            . "3. Copiar c&oacute;digo de autorizaci&oacute;n.<br>";
        
       $_SESSION['authorizeUrl'] = serialize($webAuth);
    
        session_write_close();

        header('Location: ../principal.php');
        exit();
    }elseif($token == null && isset($_POST['bttnenviar']))
    { 
        $webAuth = unserialize($_SESSION['authorizeUrl']);
        $authCode = $_POST['authcode'];
        list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
        
        $_SESSION['token'] = $accessToken;
        unset($_SESSION['dropboxAut']);
       

        $handleToken = fopen('..\data\token', 'w+');
        fwrite($handleToken, $accessToken);
        fclose($handleToken);
        

        $bakcupDAO = new BackupDAO();
        $path = $bakcupDAO->backup_tables($conexionBD->getHost(),
                    $conexionBD->getUsuario(),
                    $conexionBD->getPassword(),
                    $conexionBD->getDatabase(),
                    '*');

       $_SESSION['pathBackup'] =  $path;

        
        $dbxClient = new Dropbox\Client($token, "PHP-Example/1.0");
        $accountInfo = $dbxClient->getAccountInfo();
        
        $f = fopen($path, "rb");
        $result = $dbxClient->uploadFile("/" . $path, Dropbox\WriteMode::add(), $f);
        fclose($f);
        
        $_SESSION['resDropbox'] = $result;
        unlink($path);
        $_SESSION['backup'] = "BACKUP GENERADO";
        session_write_close();      
        
        header('Location: ../principal.php');
        exit();
        
    }else
    {
        $bakcupDAO = new BackupDAO();
        $path = $bakcupDAO->backup_tables($conexionBD->getHost(),
                    $conexionBD->getUsuario(),
                    $conexionBD->getPassword(),
                    $conexionBD->getDatabase(),
                    '*');
        $dbxClient = new Dropbox\Client($token, "PHP-Example/1.0");
        $accountInfo = $dbxClient->getAccountInfo();
        
        $f = fopen($path, "rb");
        $result = $dbxClient->uploadFile("/" . $path, Dropbox\WriteMode::add(), $f);
        fclose($f);
        
        unlink($path);   
        $_SESSION['backup'] = "BACKUP GENERADO";
        session_write_close();  
        
        header('Location: ../principal.php');
        exit();
    }
    
}


function remplazarTildez($mensaje){
    
    $aacento = utf8_decode('á');
    $eacento = utf8_decode('é');
    $iacento = utf8_decode('í');
    $oacento = utf8_decode('ó');
    $uacento = utf8_decode('ú');

    $Aacento = utf8_decode('Á');
    $Eacento = utf8_decode('É');
    $Iacento = utf8_decode('Í');
    $Oacento = utf8_decode('Ó');
    $Uacento = utf8_decode('Ú');
    
    $contilde = array('á','é','í','ó','ú','Á','É','Í','Ó','Ú');
    $conutf = array($aacento,$eacento,$iacento,$oacento,$uacento,$Aacento,$Eacento,$Iacento,$Oacento,$Uacento);
    
    return str_replace($contilde,$conutf,$mensaje);
    
}

?>
